// 引入express模块
const express = require('express')
// 引入连接池对象
const pool = require('../pool.js')
// 创建路由器对象
const user = express.Router()

user.post('/select', (req, res, next) => {
    var obj = req.body

    pool.query('select * from user_register where username=?&&userpwd=?', [obj.uname, obj.upwd], (err, data) => {
        if (err) {
            next(err)
            return
        }
        console.log(data)
        if (data.length != 0) {
            res.send({
                code: 200,
                msg: '登陆成功'
            })
        } else {
            res.send({
                code: 201,
                msg: '登陆失败'
            })
        }
    })
})

user.post('/register', (req, res, next) => {
    var obj = req.body
    console.log(obj)
    if (obj.username == '') {
        res.send({
            code: 201,
            msg: '用户名为空',
        })
        console.log('用户名不能为空值')
        return
    } else if (obj.userpwd == '') {
        res.send({
            code: 202,
            msg: '密码为空',
        })
        console.log('密码不能为空值')
        return
    } else if (obj.userrepwd == '') {
        res.send({
            code: 203,
            msg: '确认密码为空',
        })
        console.log('确认密码不能为空值')
        return
    } else if (obj.userphone == '') {
        res.send({
            code: 204,
            msg: '手机号码为空',
        })
        console.log('手机号码不能为空值')
        return
    } //用户名正则，4到16位（字母，数字，下划线，减号）
    else if (/^[a-zA-Z0-9_-]{4,16}$/.test(obj.username)) {
        res.send({
            code: 205,
            msg: '用户名格式错误'
        })
        console.log('用户名格式错误')
        return
    }  //最小长度为8位
    else if (obj.userrepwd !== obj.userpwd) {
        res.send({
            code: 206,
            msg: '密码错误'
        })
        console.log('密码错误')
        return
    } else if (!/^1[3-9]\d{9}$/.test(obj.userphone)) {
        res.send({
            code: 207,
            msg: '手机号码不合法'
        })
        console.log('手机号码不合法')
        return
    }
    pool.query('insert into user_register set?', [obj], (err, data) => {
        if (err) {
            next(err)
            console.log(err.message)
            return
        }
        console.log(data)
        res.send({
            code: 200,
            msg: '注册成功',
        })
    })
})
module.exports = user

